package com.ahui.mallchat.common.common.aspect;

import com.ahui.mallchat.common.common.annotation.RedissonLock;
import com.ahui.mallchat.common.common.service.LockService;
import com.ahui.mallchat.common.common.utils.SpELUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * Author:ahui
 * Description:
 * Date: 2024/7/23 18:03
 */
@Component
@Aspect
@Order(0) //确保比事务注解先执行，分布式锁在事务之外
public class RedissonLockAspect {

    @Autowired
    private LockService lockService;

    @Around("@annotation(redissonLock)")
    public Object around(ProceedingJoinPoint joinPoint, RedissonLock redissonLock) throws Throwable {
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        String prefix = StringUtils.isBlank(redissonLock.prefixKey()) ? SpELUtils.getMethodKey(method) :redissonLock.prefixKey();
        String key = SpELUtils.pareSpEl(method,joinPoint.getArgs(),redissonLock.key());
        return lockService.executeWithLock(prefix+":"+key,redissonLock.waitTime(),redissonLock.unit(),joinPoint::proceed);
    }
}
